<template>
    <page-container>
        <div class="flex left-right-wrap">
            <div class="left-wrap">
                <left-tree pageType="1" :isMedical="true" v-model:checked="queryParams.projectCode" @checked="handleTreeCheck"></left-tree>
            </div>
            <div class="right-wrap flex-col flex">
                <ul class="top-index flex">
                    <li :class="{ active: -1 === activeIndex }" @click="handleTopClick(-1)">全部</li>
                    <li
                        v-for="(item, index) in Object.keys(topDataMap).filter(item => item !== '0')"
                        :key="index"
                        :class="{ active: item === activeIndex }"
                        @click="handleTopClick(item)"
                    >
                        <div>
                            {{ topDataMap[item] }}
                        </div>
                    </li>
                </ul>
                <div class="ant-pro-table">
                    <div class="ant-pro-table-search companion-table">
                        <a-form layout="horizontal">
                            <a-row :gutter="15" type="flex" justify="start" :class="{ expand: expand }">
                                <a-col :xs="12" :sm="12" :md="6" :lg="4">
                                    <a-form-item>
                                        <a-input-search v-model:value="queryParams.orderNum" placeholder="工单编号" allow-clear enter-button @search="handleSearch()" />
                                    </a-form-item>
                                </a-col>
                                <a-col :xs="12" :sm="12" :md="6" :lg="4">
                                    <a-form-item>
                                        <a-input-search v-model:value="queryParams.patientName" placeholder="被陪护人姓名" allow-clear enter-button @search="handleSearch()" />
                                    </a-form-item>
                                </a-col>
                                <a-col :xs="12" :sm="12" :md="6" :lg="4">
                                    <a-form-item>
                                        <a-input-search v-model:value="queryParams.patientPhone" placeholder="被陪护人电话" allow-clear enter-button @search="handleSearch()" />
                                    </a-form-item>
                                </a-col>
                                <a-col :xs="12" :sm="12" :md="6" :lg="5">
                                    <a-form-item>
                                        <a-cascader
                                            v-model:value="queryParams.departmentId"
                                            style="width: 100%"
                                            multiple
                                            :placeholder="'请选择科室'"
                                            :options="buildData"
                                            :field-names="{ label: 'name', value: 'id', children: 'children' }"
                                            :change-on-select="false"
                                            :show-checked-strategy="Cascader.SHOW_CHILD"
                                            :max-tag-count="1"
                                            @change="handleSearch()"
                                        ></a-cascader>
                                    </a-form-item>
                                </a-col>
                                <a-col :xs="12" :sm="12" :md="6" :lg="3">
                                    <a-form-item>
                                        <a-select
                                            ref="select"
                                            v-model:value="queryParams.orderSource"
                                            placeholder="工单来源"
                                            :options="[
                                                {
                                                    label: '全部',
                                                    value: '',
                                                },
                                                {
                                                    label: '用户下单',
                                                    value: 0,
                                                },
                                                {
                                                    label: '员工下单',
                                                    value: 1,
                                                },
                                            ]"
                                            allow-clear
                                            @change="handleSearch()"
                                        ></a-select>
                                    </a-form-item>
                                </a-col>

                                <template v-if="expand">
                                    <a-col :xs="12" :sm="12" :md="6" :lg="4">
                                        <a-form-item>
                                            <a-select
                                                v-model:value="queryParams.carerId"
                                                mode="multiple"
                                                :max-tag-count="1"
                                                placeholder="陪护人员"
                                                allow-clear
                                                :options="
                                                    dictData.carersList.map(item => ({
                                                        ...item,
                                                        label: item.name,
                                                        value: item.id,
                                                    }))
                                                "
                                                :filter-option="filterOption"
                                                @change="handleSearch()"
                                                style="width: 100%"
                                            ></a-select>
                                        </a-form-item>
                                    </a-col>
                                    <a-col :xs="12" :sm="12" :md="6" :lg="4">
                                        <a-form-item>
                                            <a-select
                                                ref="select"
                                                v-model:value="queryParams.serviceId"
                                                placeholder="陪护类型"
                                                mode="multiple"
                                                :options="
                                                    dictData.typesData.map(item => ({
                                                        ...item,
                                                        label: item.name,
                                                        value: item.id,
                                                    }))
                                                "
                                                :max-tag-count="1"
                                                allow-clear
                                                @change="handleServiceTypeChange"
                                            ></a-select>
                                        </a-form-item>
                                    </a-col>
                                    <!-- <a-col :xs="12" :sm="12" :md="6" :lg="3">
                                        <a-form-item>
                                            <a-select
                                                mode="multiple"
                                                v-model:value="queryParams.serviceTypeId"
                                                :placeholder="queryParams.serviceId ? '陪护标准' : '先选择陪护类型'"
                                                :options="dictData"
                                                allow-clear
                                                @change="handleSearch()"
                                            ></a-select>
                                        </a-form-item>
                                    </a-col> -->
                                    <a-col :xs="12" :sm="12" :md="7" :lg="6">
                                        <a-form-item>
                                            <a-range-picker
                                                v-model:value="queryParams.appointedTime"
                                                :placeholder="['预约开始时间', '预约结束时间']"
                                                allow-clear
                                                @change="handleSearch()"
                                            />
                                        </a-form-item>
                                    </a-col>
                                    <a-col :xs="12" :sm="12" :md="7" :lg="6">
                                        <a-form-item>
                                            <a-range-picker
                                                v-model:value="queryParams.actualTime"
                                                :placeholder="['陪护开始时间', '陪护结束时间']"
                                                allow-clear
                                                @change="handleSearch()"
                                            />
                                        </a-form-item>
                                    </a-col>
                                    <a-col :xs="12" :sm="12" :md="7" :lg="6">
                                        <a-form-item>
                                            <a-range-picker
                                                v-model:value="queryParams.payTime"
                                                :placeholder="['支付开始时间', '支付结束时间']"
                                                allow-clear
                                                @change="handleSearch()"
                                            />
                                        </a-form-item>
                                    </a-col>
                                    <a-col :xs="12" :sm="12" :md="6" :lg="4">
                                        <a-form-item>
                                            <a-select
                                                v-model:value="queryParams.invoiceUpload"
                                                placeholder="发票是否上传"
                                                :options="
                                                    Object.keys(invoiceUploadMap).map(item => ({
                                                        label: invoiceUploadMap[item],
                                                        value: Number(item),
                                                    }))
                                                "
                                                @change="handleSearch()"
                                                allow-clear
                                            ></a-select>
                                        </a-form-item>
                                    </a-col>
                                </template>
                                <a-col :xs="24" :sm="24" :md="12" :lg="4">
                                    <!-- <a-button @click="handleSearch" type="primary">搜索</a-button> -->
                                    <a-button @click="handleReset" class="ml-5px">重置</a-button>
                                    <a-button type="text" class="ml-5px" @click="expand = !expand">
                                        <template v-if="expand">
                                            <up-outlined />
                                        </template>
                                        <template v-else>
                                            <down-outlined />
                                        </template>
                                    </a-button>
                                </a-col>
                            </a-row>
                        </a-form>
                    </div>
                    <a-card :body-style="{ padding: 0 }" ref="elRef">
                        <div class="ant-pro-table-list-toolbar">
                            <div class="ant-pro-table-list-toolbar-container">
                                <div class="ant-pro-table-list-toolbar-left">
                                    <!-- <div class="ant-pro-table-list-toolbar-title">查询表格</div> -->
                                </div>
                                <div class="ant-pro-table-list-toolbar-right">
                                    <a-space align="center">
                                        <a-button @click="handleExport" class="ml-10px" :loading="exportLoading" v-permission="[`yfwy:medical-caregiver-order:export`]">
                                            <download-outlined />
                                            导出
                                        </a-button>

                                        <a-button @click="handleExport2" class="ml-10px" :loading="exportLoading2" v-permission="[`yfwy:medical-caregiver-order:export`]">
                                            <download-outlined />
                                            导出发票工单
                                        </a-button>

                                        <div class="ant-pro-table-list-toolbar-setting-item">
                                            <a-tooltip title="表格斑马纹">
                                                <a-switch checked-children="开" un-checked-children="关" v-model:checked="fetchDataContext.stripe" />
                                            </a-tooltip>
                                        </div>
                                    </a-space>
                                    <div class="ant-pro-table-list-toolbar-divider">
                                        <a-divider type="vertical" />
                                    </div>
                                    <div class="ant-pro-table-list-toolbar-setting-item">
                                        <a-tooltip title="刷新">
                                            <reload-outlined @click="reload" />
                                        </a-tooltip>
                                    </div>
                                    <div class="ant-pro-table-list-toolbar-setting-item">
                                        <a-tooltip title="密度">
                                            <a-dropdown :trigger="['click']" placement="bottomRight">
                                                <column-height-outlined />
                                                <template #overlay>
                                                    <a-menu
                                                        style="width: 80px"
                                                        :selected-keys="[state.tableSize]"
                                                        @click="
                                                            ({ key }) => {
                                                                fetchDataContext.tableSize = String(key);
                                                            }
                                                        "
                                                    >
                                                        <a-menu-item key="default">
                                                            <a href="javascript:;">默认</a>
                                                        </a-menu-item>
                                                        <a-menu-item key="middle">
                                                            <a href="javascript:;">中等</a>
                                                        </a-menu-item>
                                                        <a-menu-item key="small">
                                                            <a href="javascript:;">紧凑</a>
                                                        </a-menu-item>
                                                    </a-menu>
                                                </template>
                                            </a-dropdown>
                                        </a-tooltip>
                                    </div>
                                    <div class="ant-pro-table-list-toolbar-setting-item">
                                        <a-popover placement="bottomRight" arrowPointAtCenter trigger="click" overlayClassName="ant-pro-table-column-setting-overlay">
                                            <template #title>
                                                <div class="ant-pro-table-column-setting-title">
                                                    <a-checkbox v-model:checked="columnState.checkAll" :indeterminate="columnState.indeterminate" @change="handleColumnAllClick">
                                                        列展示 / 排序
                                                    </a-checkbox>
                                                    <a @click="reset">重置</a>
                                                </div>
                                            </template>
                                            <template #content>
                                                <span class="ant-pro-table-column-setting-list">
                                                    <drag-container
                                                        lockAxis="y"
                                                        dragClass="ant-pro-table-drag-ghost"
                                                        dropClass="ant-pro-table-drop-ghost"
                                                        @drop="({ removedIndex, addedIndex }) => move(removedIndex, addedIndex)"
                                                    >
                                                        <template v-for="column in dynamicColumnItems" :key="column.key">
                                                            <draggable>
                                                                <div class="ant-pro-table-column-setting-list-item">
                                                                    <drag-icon />
                                                                    <a-checkbox :checked="column.checked" @change="handleColumnChange($event, column)">
                                                                        {{ column.label }}
                                                                    </a-checkbox>
                                                                </div>
                                                            </draggable>
                                                        </template>
                                                    </drag-container>
                                                </span>
                                            </template>
                                            <a-tooltip title="列设置">
                                                <setting-outlined />
                                            </a-tooltip>
                                        </a-popover>
                                    </div>
                                    <!-- <div class="ant-pro-table-list-toolbar-setting-item">
                                        <a-tooltip :title="screenState ? '退出全屏' : '全屏'">
                                            <fullscreen-outlined v-if="!screenState" @click="setFull" />
                                            <fullscreen-exit-outlined v-else @click="exitFull" />
                                        </a-tooltip>
                                    </div> -->
                                </div>
                            </div>
                        </div>
                        <a-table
                            :row-class-name="stripe"
                            :size="state.tableSize"
                            :loading="state.loading"
                            :columns="dynamicColumns"
                            :data-source="state.dataSource"
                            :pagination="{
                                'show-size-changer': true,
                                current: state.current,
                                pageSize: state.pageSize,
                                total: state.total,
                                showTotal: total => `共 ${total} 条`,
                            }"
                            ref="tableRef"
                            :getPopupContainer="_trigger => tableRef.$el"
                            :scroll="{ x: 1150, y: appStore.tableHeight - 12 - (!expand ? 44 : 108) }"
                            @change="handleTableChange"
                        >
                            <template #bodyCell="{ column, record }">
                                <template v-if="column.dataIndex === 'orderNum'">
                                    <div @click="handleOrderClick(record)" class="order-no">
                                        {{ record.orderNum }}
                                    </div>
                                </template>
                                <template v-else-if="column.dataIndex === 'appointedTime'">
                                    {{ [(record.appointedStartTime || '').slice(0, -3), (record.appointedEndTime || '').slice(0, -3)].filter(Boolean).join('/') }}
                                </template>
                                <template v-else-if="column.dataIndex === 'status'">
                                    {{ topDataMap[record.orderState] }}
                                </template>
                                <template v-else-if="column.dataIndex === 'paymentType'">
                                    {{ paymentTypeMap[record.paymentType] }}
                                </template>

                                <template v-else-if="column.dataIndex === 'projectName'">
                                    {{
                                        [record.projectName, record.buildingName, record.floorName, record.departmentName, record.bedNum ? record.bedNum + '床' : '']
                                            .filter(Boolean)
                                            .join('-')
                                    }}
                                </template>
                                <template v-else-if="column.dataIndex === 'appointedDay'">{{ record.appointedDay || '0' }}天</template>
                                <template v-else-if="column.dataIndex === 'actualDay'">{{ record.actualDay || '0' }}天</template>
                                <template v-else-if="column.dataIndex === 'orderSource'">{{ orderSourceMap[record.orderSource] }}</template>
                                <template v-else-if="column.dataIndex === 'action'">
                                    <a-button>审核</a-button>
                                </template>
                            </template>
                        </a-table>
                    </a-card>
                </div>
            </div>
        </div>
        <info-modal :model="orderInfoModal" :visible="infoModalVisible" @cancel="infoModalVisible = false" @success="reload()" />
    </page-container>
</template>

<script lang="ts">
    import { statusMap, orderSourceMap, paymentTypeMap, invoiceUploadMap } from './common';
    import { defineComponent, reactive, ref, watch, watchEffect, onMounted, computed, nextTick } from 'vue';
    import {
        PlusOutlined,
        ReloadOutlined,
        ColumnHeightOutlined,
        SettingOutlined,
        FullscreenOutlined,
        FullscreenExitOutlined,
        DownOutlined,
        UpOutlined,
        DownloadOutlined,
        RetweetOutlined,
    } from '@ant-design/icons-vue';
    import EventBus from '@/utils/eventBus';
    import { Container as DragContainer, Draggable } from '@/components/draggable';
    import { pagePendingReview, pageApproved, pageNotify, updateReadState } from '@/api/order/mine-list';
    import { getMedicalCaregiverOrderPage, exportMedicalCaregiverOrderExcel, exportMedicalCaregiverOrderExcelInvoice } from '@/api/companion/order';
    import { getMedicalCaregiverTypePage } from '@/api/companion/cate';
    import { getMedicalCaregiverCarerPage } from '@/api/companion/porter';

    import { queryDeptsByProjectcodes } from '@/api/list/department';
    import type { Pagination, TableFilters, TableColumn } from '@/typing';
    import { useFetchData } from '@/utils/hooks/useFetchData';
    import { useFullscreen } from '@/utils/hooks/useFullscreen';
    import { useTableDynamicColumns } from '@/utils/hooks/useTableColumn';
    import DragIcon from '@/components/table/drag-icon.vue';
    import InfoModal from './order-info-modal.vue';
    import dayjs from 'dayjs';
    import { downloadByData } from '@/utils/download';
    import { isEmpty, isUndefined, isArray } from 'lodash-es';
    import { useAppStore } from '@/store/app';
    import { useUserStore } from '@/store/user';
    import { recursionMapTree } from '../porter/common';
    import { message, Cascader } from 'ant-design-vue';

    const appStore = useAppStore();
    const userStore = useUserStore();

    export default defineComponent({
        name: 'TableList',
        setup() {
            const tableRef = ref();
            const exportLoading = ref<boolean>(false);
            const exportLoading2 = ref<boolean>(false);
            const expand = ref<boolean>(false);
            const activeIndex = ref<number>(-1);

            const dictData = reactive<any>({
                carersList: [],
            });
            const buildData = ref<any>([]);
            const topData = ref<any[]>([]);
            const topDataMap = statusMap;

            const filteredInfoMap = ref();
            const queryParams = reactive<any>({
                orderState: activeIndex.value,
                departmentId: [],
                carerId: [],
            });
            if (activeIndex.value >= 0) {
                queryParams.orderState = activeIndex.value;
            } else {
                delete queryParams.orderState;
            }
            const fetchDataContext = reactive<any>({
                current: 1,
                pageSize: 50,
                tableSize: 'middle', // 'default' | 'middle' | 'small'
                stripe: false,
                executeImmediately: false,
                requestParams: { ...queryParams },
            });
            watch(
                filteredInfoMap,
                () => {
                    // queryParams.status = filteredInfoMap.value?.status;
                    // fetchDataContext.requestParams = { ...queryParams };
                },
                { immediate: true },
            );
            const mergedColumns = ref<TableColumn[]>([]);
            watchEffect(() => {
                const baseColumns: TableColumn[] = [
                    {
                        title: '工单编号',
                        dataIndex: 'orderNum',
                        width: 140,
                        ellipsis: true,
                        fixed: 'left',
                    },
                    {
                        title: '下单时间',
                        dataIndex: 'createTime',
                        width: 160,
                        ellipsis: true,
                    },
                    {
                        title: '下单人',
                        dataIndex: 'orderPerson',
                        width: 80,
                        ellipsis: true,
                    },
                    {
                        title: '下单支付时间',
                        dataIndex: 'payTime',
                        width: 160,
                        ellipsis: true,
                    },
                    {
                        title: '支付方式',
                        dataIndex: 'paymentType',
                        width: 80,
                        ellipsis: true,
                    },
                    {
                        title: '工单状态',
                        dataIndex: 'status',
                        width: 80,
                        ellipsis: true,
                    },
                    {
                        title: '工单来源',
                        dataIndex: 'orderSource',
                        width: 80,
                        ellipsis: true,
                    },
                    {
                        title: '科室',
                        dataIndex: 'projectName',
                        width: 400,
                        ellipsis: true,
                    },
                    {
                        title: '被陪护人名称',
                        dataIndex: 'patientName',
                        width: 110,
                        ellipsis: true,
                    },
                    {
                        title: '被陪护人电话',
                        dataIndex: 'patientPhone',
                        width: 110,
                        ellipsis: true,
                    },
                    {
                        title: '陪护类型',
                        dataIndex: 'serviceName',
                        width: 120,
                        ellipsis: true,
                    },
                    {
                        title: '陪护标准',
                        dataIndex: 'serviceTypeName',
                        width: 120,
                        ellipsis: true,
                    },
                    {
                        title: '预约时间区间',
                        dataIndex: 'appointedTime',
                        width: 300,
                        ellipsis: true,
                    },
                    {
                        title: '预约天数',
                        dataIndex: 'appointedDay',
                        width: 80,
                        ellipsis: true,
                    },
                    {
                        title: '陪护开始时间',
                        dataIndex: 'actualStartTime',
                        width: 160,
                        ellipsis: true,
                    },
                    {
                        title: '陪护结束时间',
                        dataIndex: 'actualEndTime',
                        width: 160,
                        ellipsis: true,
                    },
                    {
                        title: '陪护天数',
                        dataIndex: 'actualDay',
                        width: 80,
                        ellipsis: true,
                    },
                    {
                        title: '护理人',
                        dataIndex: 'carer',
                        width: 160,
                        ellipsis: true,
                    },
                ];
                const lastColumns: TableColumn[] = [
                    {
                        title: '费用',
                        dataIndex: 'priceNormal',
                        width: 90,
                        ellipsis: true,
                    },
                    {
                        title: '退款金额',
                        dataIndex: 'refundPrice',
                        width: 90,
                        ellipsis: true,
                    },
                ];
                mergedColumns.value = computed(() => {
                    if ([0, 1, 2, 5, 6].includes(activeIndex.value)) {
                        return [
                            ...baseColumns,
                            {
                                title: '联系电话',
                                dataIndex: 'score',
                                width: 160,
                            },
                            ...lastColumns,
                        ];
                    }
                    return [
                        ...baseColumns,
                        ...lastColumns,
                        {
                            title: '实际费用',
                            dataIndex: 'actualPrice',
                            width: 100,
                            ellipsis: true,
                        },
                        {
                            title: '发票是否上传',
                            dataIndex: 'invoiceUpload',
                            width: 100,
                            ellipsis: true,
                            customRender: ({ text }) => invoiceUploadMap[text],
                        },
                        {
                            title: '综合评分',
                            dataIndex: 'score',
                            width: 80,
                            ellipsis: true,
                        },
                    ];
                });
            });
            const needRowIndex = ref(false);

            const {
                state: columnState,
                dynamicColumns,
                dynamicColumnItems,
                handleColumnAllClick,
                handleColumnChange,
                reset,
                move,
            } = useTableDynamicColumns(mergedColumns.value, { needRowIndex });

            const [elRef, screenState, { setFull, exitFull }] = useFullscreen();

            const { stripe, context: state, reload } = useFetchData(getMedicalCaregiverOrderPage, fetchDataContext);

            onMounted(() => {
                // if (window.sessionStorage.getItem('openOrder')) {
                //     Object.keys(orderInfoModal).forEach(key => {
                //         delete orderInfoModal[key];
                //     });
                //     Object.assign(orderInfoModal, { orderNum: window.sessionStorage.getItem('openOrder') });
                //     window.sessionStorage.setItem('openOrder', '');
                //     infoModalVisible.value = true;
                // }
                // EventBus.on('reloadOrder', (data: any) => {
                //     window.sessionStorage.setItem('openOrder', '');
                //     dotShow.value = data.dotShow;

                //     handleReset();
                //     Object.keys(orderInfoModal).forEach(key => {
                //         delete orderInfoModal[key];
                //     });
                //     Object.assign(orderInfoModal, { orderNum: data.orderId });
                //     infoModalVisible.value = true;
                //     // console.log(11, window.sessionStorage.getItem('openOrder'));

                //     // if (window.sessionStorage.getItem('openOrder')) {
                //     //     orderInfoModal.orderNum = window.sessionStorage.getItem('openOrder');
                //     //     infoModalVisible.value = true;
                //     //     window.sessionStorage.removeItem('openOrder');
                //     // }
                // });

                Promise.all([
                    getMedicalCaregiverTypePage({
                        current: 1,
                        size: 10000,
                    }),
                ]).then(res => {
                    const [cateData] = res;
                    dictData.typesData = cateData.data.records;
                });
            });

            const handleServiceTypeChange = (val: any) => {
                handleSearch();
            };

            const formatSource = (source: string) => {
                if (isUndefined(source) || isEmpty(dictData.xmytData)) return '';
                return dictData.xmytData.find(item => item.value === source)?.label || '';
            };

            const handleTreeCheck = (
                checkedKeys,
                e: any,
                // e: { checked: boolean; checkedNodes; node; event },
            ) => {
                queryParams.projectCode = checkedKeys;
                queryParams.departmentId = [];
                fetchDataContext.executeImmediately = true;
                handleSearch();

                getMedicalCaregiverCarerPage({
                    projectCode: checkedKeys,
                    size: 10000,
                    current: 1,
                }).then(res => {
                    dictData.carersList = res.data.records;
                });

                queryDeptsByProjectcodes(checkedKeys).then(res => {
                    // 查询科室
                    buildData.value = recursionMapTree(res.data, 1, 4);
                });
            };

            const handleTableChange = ({ current, pageSize }: Pagination, filters?: TableFilters) => {
                filteredInfoMap.value = filters;
                fetchDataContext.current = current;
                fetchDataContext.pageSize = pageSize;
            };

            const handleSearch = () => {
                fetchDataContext.current = 1;
                const { actualTime = [], appointedTime = [], payTime = [], orderState, departmentId = [], ...params } = queryParams;
                console.log(departmentId);

                if (!isEmpty(actualTime) && actualTime.length === 2) {
                    params.actualStartTime = dayjs(actualTime[0]).format('YYYY-MM-DD') + ' 00:00:00';
                    params.actualEndTime = dayjs(actualTime[1]).format('YYYY-MM-DD') + ' 23:59:59';
                }
                if (!isEmpty(appointedTime) && appointedTime.length === 2) {
                    params.appointedStartTime = dayjs(appointedTime[0]).format('YYYY-MM-DD') + ' 00:00:00';
                    params.appointedEndTime = dayjs(appointedTime[1]).format('YYYY-MM-DD') + ' 23:59:59';
                }
                if (!isEmpty(payTime) && payTime.length === 2) {
                    params.payTimeStart = dayjs(payTime[0]).format('YYYY-MM-DD') + ' 00:00:00';
                    params.payTimeEnd = dayjs(payTime[1]).format('YYYY-MM-DD') + ' 23:59:59';
                }
                if (departmentId.length > 0) {
                    params.departmentId = departmentId.map(item => item.at(-1));
                }

                fetchDataContext.requestParams = { ...params, orderState: orderState > 0 ? [orderState] : null };
            };
            const handleReset = () => {
                Object.keys(queryParams).forEach(key => {
                    if (key !== 'projectCode') {
                        delete queryParams[key];
                    }
                });
                queryParams.orderTime = [];
                handleSearch();
            };

            // modal
            const orderInfoModal = reactive<any>({});
            const infoModalVisible = ref(false);

            const handleExport = () => {
                exportLoading.value = true;
                exportMedicalCaregiverOrderExcel({
                    ...fetchDataContext.requestParams,
                    size: 1000000,
                    orderState: isArray(fetchDataContext.requestParams.orderState) ? fetchDataContext.requestParams.orderState : [],
                })
                    .then(res => {
                        downloadByData(res, `${topDataMap[activeIndex.value] ? topDataMap[activeIndex.value] : ''}工单.xlsx`);
                    })
                    .finally(() => {
                        exportLoading.value = false;
                    });
            };

            const handleExport2 = () => {
                exportLoading2.value = true;
                exportMedicalCaregiverOrderExcelInvoice({
                    ...fetchDataContext.requestParams,
                    orderState: [4, 7],
                    size: 1000000,
                })
                    .then(res => {
                        downloadByData(res, `发票工单.xlsx`);
                    })
                    .finally(() => {
                        exportLoading2.value = false;
                    });
            };

            const handleTopClick = index => {
                activeIndex.value = index;
                if (index > 0) {
                    queryParams.orderState = index;
                } else {
                    delete queryParams.orderState;
                }
                if ([3].includes(index)) {
                    fetchDataContext.queryMethod = pagePendingReview;
                    if (topData.value[index].num > 0 && topData.value[index].readState == 0) {
                        updateReadState({ projectCode: queryParams.projectCode, orderState: 3 }).then(() => {
                            // getTypeAndNum(queryParams.projectCode).then(res => {
                            //     topData.value = res.data;
                            // });
                        });
                    }
                    // delete queryParams.orderState;
                } else if ([4].includes(index)) {
                    fetchDataContext.queryMethod = pageApproved;
                    // delete queryParams.orderState;
                } else if ([9].includes(index)) {
                    fetchDataContext.queryMethod = pageNotify;
                    // delete queryParams.orderState;
                } else {
                    fetchDataContext.queryMethod = getMedicalCaregiverOrderPage;
                }

                handleSearch();
            };

            const handleOrderClick = row => {
                Object.keys(orderInfoModal).forEach(key => {
                    delete orderInfoModal[key];
                });
                Object.assign(orderInfoModal, row);
                infoModalVisible.value = true;
            };

            const filterOption = (input: string, option: any) => {
                console.log(option.value);

                return option.value.name.includes(input);
            };

            return {
                filterOption,
                userStore,
                EventBus,
                appStore,
                activeIndex,
                handleTopClick,
                dictData,
                reload,
                state,
                stripe,
                columnState,
                dynamicColumns,
                dynamicColumnItems,
                queryParams,
                handleSearch,
                handleReset,
                // fullscreen
                elRef,
                screenState,
                setFull,
                exitFull,

                handleTableChange,
                handleColumnChange,
                handleColumnAllClick,
                reset,
                move,

                // modal controls
                infoModalVisible,
                orderInfoModal,

                tableRef,
                fetchDataContext,
                handleTreeCheck,
                handleExport,
                handleExport2,
                exportLoading,
                exportLoading2,

                formatSource,
                expand,

                topDataMap,
                topData,

                handleOrderClick,
                handleServiceTypeChange,
                buildData,
                Cascader,
                orderSourceMap,
                paymentTypeMap,
                invoiceUploadMap
            };
        },
        components: {
            DragIcon,
            PlusOutlined,
            ReloadOutlined,
            ColumnHeightOutlined,
            SettingOutlined,
            FullscreenOutlined,
            FullscreenExitOutlined,
            DownOutlined,
            UpOutlined,
            DownloadOutlined,
            RetweetOutlined,
            Draggable,
            DragContainer,
            InfoModal,
            Cascader,
        },
    });
</script>

<style lang="less" scoped>
    .ant-row {
        &.expand {
            .ant-col {
                margin-bottom: 10px;
            }
        }
    }

    .order-no {
        text-decoration: underline;
        cursor: pointer;
        color: #1890ff;
    }

    .top-index {
        width: 100%;
        background: #fff;
        li {
            list-style: none;
            flex: 1;
            text-align: center;
            line-height: 50px;
            cursor: pointer;
            &.active,
            &:hover {
                color: #1677ff;
                font-weight: bold;
            }
        }
    }
</style>
